import React, { useState } from 'react';
import { Editor } from '@monaco-editor/react';
import { useRepoStore } from '@/store/useRepoStore';
import { useEditorStore } from '@/store/useEditorStore';

const FileViewer: React.FC = () => {
  const { currentFile, saveFile } = useRepoStore();
  const { 
    isEditing, 
    currentContent, 
    originalContent,
    language,
    theme,
    fontSize,
    isDirty,
    updateContent,
    discardChanges,
    resetEditor
  } = useEditorStore();
  
  const [isSaving, setIsSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  const handleEditorChange = (value: string | undefined) => {
    if (value !== undefined) {
      updateContent(value);
    }
  };

  const handleSave = async () => {
    if (!currentFile) return;
    
    try {
      setIsSaving(true);
      setSaveError(null);
      await saveFile(currentFile.path, currentContent);
      // 保存成功后重置编辑状态
      resetEditor();
    } catch (error) {
      console.error('保存文件失败', error);
      setSaveError(error instanceof Error ? error.message : '保存文件失败');
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    discardChanges();
  };

  if (!isEditing || !currentFile) {
    return (
      <div className="flex flex-col items-center justify-center h-64 text-gray-500 dark:text-gray-400">
        <svg className="h-12 w-12 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <p>选择一个文件以查看其内容</p>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col">
      <div className="flex justify-between items-center mb-2">
        <h3 className="text-sm font-medium text-gray-900 dark:text-white truncate">
          {currentFile.name}
        </h3>
        <div className="flex space-x-2">
          {isDirty && (
            <>
              <button
                onClick={handleCancel}
                className="px-2 py-1 text-xs text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"
                disabled={isSaving}
              >
                取消
              </button>
              <button
                onClick={handleSave}
                className="px-2 py-1 text-xs text-white bg-green-600 hover:bg-green-700 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={isSaving}
              >
                {isSaving ? '保存中...' : '保存'}
              </button>
            </>
          )}
        </div>
      </div>
      
      {saveError && (
        <div className="mb-2 text-sm text-red-600 bg-red-100 p-2 rounded-md dark:bg-red-900 dark:text-red-200">
          {saveError}
        </div>
      )}
      
      <div className="flex-grow border border-gray-200 dark:border-gray-700 rounded-md overflow-hidden">
        <Editor
          height="60vh"
          language={language}
          value={currentContent}
          theme={theme === 'dark' ? 'vs-dark' : 'light'}
          onChange={handleEditorChange}
          options={{
            readOnly: false,
            minimap: { enabled: true },
            scrollBeyondLastLine: false,
            fontSize: fontSize,
            wordWrap: 'on',
            automaticLayout: true,
          }}
        />
      </div>
    </div>
  );
};

export default FileViewer;